package com.boe.csb.web.controller.base;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.boe.csb.core.common.exception.CSBErrorCode;
import com.boe.csb.core.common.exception.CSBException;
import com.boe.csb.core.common.status.AdminUserRole;
import com.boe.csb.core.common.status.CertificationStatus;
import com.boe.csb.core.common.utils.MD5Utils;
import com.boe.csb.core.dao.BoeUserCriteria;
import com.boe.csb.core.dao.BoeUserMapper;
import com.boe.csb.core.dao.UserOperateLogMapper;
import com.boe.csb.core.entity.SimplePageInfo;
import com.boe.csb.core.entity.UserInfo;
import com.boe.csb.core.entity.dto.BoeUserNameDTO;
import com.boe.csb.core.entity.po.BoeAppBean;
import com.boe.csb.core.entity.po.BoeUser;
import com.boe.csb.core.entity.po.UserOperateLog;
import com.boe.csb.core.service.user.AdminUserService;
import com.boe.csb.core.service.user.BoeAppService;
import com.boe.csb.core.service.user.BoeUserService;
import com.boe.csb.web.controller.BaseController;
import com.boe.csb.web.model.ResultModel;


/**
 * Created by louie on 2016/11/17.
 */
@RequestMapping("/api/admin/")
@RestController
public class AdminUserController extends BaseController {

    private final static String REST_PASSWORD = "123456";

    @Autowired
    private BoeUserService boeUserService;
    @Autowired
    private BoeUserMapper boeUserMapper;
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private UserOperateLogMapper userOperateLogMapper;
    @Autowired
    private BoeAppService boeAppService;



    /**
     * 用户认证审核列表V2
     */
    @RequestMapping(value = "certification/list")
    public ResultModel<SimplePageInfo> listCertification( @RequestParam Integer pageNum, @RequestParam Integer limit,@RequestParam(required = false) String type,@RequestParam(required = false)String status){
        return ResultModel.success(new SimplePageInfo(boeUserService.listCertification(pageNum, limit,type,status), boeUserService.countCertificationList(type,status)));
    }

    /**
     * 管理员审核用户认证
     *
     * @param status
     * @return
     */
    @RequestMapping(value = "certification",method = RequestMethod.POST)
    public ResultModel<Void> certification(HttpSession session, @RequestParam List<Long> idList, @RequestParam String status,@RequestParam(required = false) String comment) {
        String userId = fetchUserId(session);
        boeUserService.updateCertificationStatus(idList, status, userId,comment);
        return ResultModel.success(null);
    }


    /**
     * 修改用户的角色
     */
    @RequestMapping(value = "update/user/role")
    public ResultModel<Void> updateUserRole(HttpSession session,@RequestParam Long userId, @RequestParam String role, @RequestParam String power) {

        //纪录日志
        String adminId = String.valueOf(fetchUserInfo(session).getUserId());
        String userName = fetchUserInfo(session).getUserName();
        String log = boeUserService.findBoeUser(String.valueOf(userId)).getEmail();
        String remark = String.format("管理员%s修改了用户%s角色",userName,log);
        userOperateLogMapper.insert(new UserOperateLog(Long.valueOf(adminId),userName,log, AdminUserRole.ACCOUNT_MANAGER.getRole(),remark,new Date()));

        String[] str = power.split(";");
        boeUserMapper.updateAdminUserPower(Long.valueOf(userId),str[0],str[1]);
        
        boeUserService.updateBoeUserRole(userId, role);
        return ResultModel.success(null);
    }

    /**
     * 修改密码
     */
    @RequestMapping(value = "reset/password")
    public ResultModel<Void> resetPassword(@RequestParam Long userId) {
        boeUserService.resetPassword(userId, REST_PASSWORD);
        return ResultModel.success(null);
    }
    


    /**
     * 分页获取的管理员
     */
    @RequestMapping(value = "/all/admin", method = RequestMethod.GET)
    public ResultModel<SimplePageInfo> queryAllAdmin(@RequestParam Integer pageNum, @RequestParam Integer limit) {
        BoeUserCriteria criteria = new BoeUserCriteria();
        criteria.createCriteria().andIsAdminEqualTo(true).andAuditStatusEqualTo(CertificationStatus.ALLOW.getStatus()).andCantModifyNotEqualTo(Boolean.TRUE);
        criteria.setOrderByClause("gmt_modified desc");
        List<BoeUser> boeUserList = boeUserMapper.selectByExampleWithBLOBsWithRowbounds(criteria, new RowBounds(((pageNum - 1) * limit), limit));
        for(int i=0;i<boeUserList.size();i++){
        	BoeUser bean = boeUserList.get(i);
        	String name = bean.getEmail();
        	bean.setEmail(bean.getQq());
        	bean.setQq(name);
        }
        long count = boeUserMapper.countByExample(criteria);
        return ResultModel.success(new SimplePageInfo(boeUserList,count));
    }

    /**
     * 获取所有的管理员
     */
    @RequestMapping(value = "/list/all/admin",method = RequestMethod.GET)
    public ResultModel<List<BoeUserNameDTO>> listAllAdmin(){
        List<BoeUserNameDTO> adminList = new ArrayList<>();
        BoeUserCriteria criteria = new BoeUserCriteria();
        criteria.createCriteria().andIsAdminEqualTo(true).andAuditStatusEqualTo(CertificationStatus.ALLOW.getStatus());
        List<BoeUser> boeUserList = boeUserMapper.selectByExample(criteria);
        for (BoeUser boeUser:boeUserList){
            BoeUserNameDTO dto = new BoeUserNameDTO();
            dto.setId(boeUser.getId());
            dto.setName(boeUser.getEmail());
            adminList.add(dto);
        }
        return ResultModel.success(adminList);
    }


    /**
     * 创建管理员
     */
    @RequestMapping(value = "/create/admin", method = RequestMethod.POST)
    public ResultModel<Object> createAdmin(HttpSession session, String loginId, String password,String email) {
        String adminId = fetchUserId(session);
        if (loginId == null || password == null) {
            return ResultModel.fail(CSBErrorCode.BASIC_ERROR, "注册失败");
        }
        
        BoeUser boeUser = new BoeUser();
        boeUser.setEmail(loginId);
        boeUser.setQq(email);
        boeUser.setActiveStatus(Byte.valueOf("1"));
        boeUser.setPassword(MD5Utils.getMD5String(password));
        boeUser.setAuditStatus(CertificationStatus.ALLOW.getStatus());
        boeUser.setIsAdmin(true);
        boeUser.setCantModify(Boolean.FALSE);
        CSBErrorCode errCode = boeUserService.createAdmin(adminId, boeUser);
        return errCode == CSBErrorCode.SUCCESS ? ResultModel.success(null) : ResultModel.fail(errCode, null); 
    }


    /**
     * 删除用户
     *
     * @param userId
     * @return
     */
    @RequestMapping(value = "/delete/admin",method = RequestMethod.POST)
    public ResultModel<Void> deleteAdmin(HttpSession session,Long userId) {
        //管理员不能删除自己
        if(fetchUserId(session).equals(String.valueOf(userId))){
            throw new CSBException(CSBErrorCode.ADMIN_CANT_DELETE_MYSELF,"");
        }
        BoeUser boeUser = new BoeUser();
        boeUser.setAuditStatus(CertificationStatus.REJECT.getStatus());
        BoeUserCriteria criteria = new BoeUserCriteria();
        criteria.createCriteria().andIdEqualTo(userId).andIsAdminEqualTo(Boolean.TRUE).andCantModifyEqualTo(Boolean.FALSE);
        boeUserMapper.deleteByExample(criteria);
        return ResultModel.success(null);
    }

    /**
     * 管理员权限
     */
    @RequestMapping(value = "roles")
    public ResultModel<List<String>> roles() {
        List<String> roles = new ArrayList<>();
        for (AdminUserRole adminUserRole : AdminUserRole.values()) {
            roles.add(adminUserRole.getRole());
        }
        return ResultModel.success(roles);
    }

    /**
     * 查看日志功能
     * @param pageNum
     * @param limit
     * @return
     */
    @RequestMapping(value = "view/log")
    public ResultModel<SimplePageInfo> viewLog(@RequestParam int pageNum,
                                               @RequestParam int limit,
                                               @RequestParam(required = false) Long userId,
                                               @RequestParam(required = false) String type){
        List<UserOperateLog> list =adminUserService.viewLog(userId,type,pageNum,limit);
        for(UserOperateLog log:list){
           log.setLogType(AdminUserRole.map.get(log.getLogType()));
        }
        long count = adminUserService.countLog(userId,type);
        return ResultModel.success(new SimplePageInfo(list,count));
    }
 
    @RequestMapping(value = "clear/session")
    public ResultModel<Void> clearEditSession(HttpServletRequest request,HttpServletResponse response){
    	System.out.println("=================================");
    	String session = "";
    	Cookie[] ss = request.getCookies();
    	for(int i =0;i<ss.length;i++){
    		if("SESSION".equals(ss[i].getName())){
    			session = ss[i].getValue();
    			System.out.println(i+"===="+ss[i].getName());
        		System.out.println(i+"===="+session);
    		}
    		//cookie设置为0
    		ss[i].setMaxAge(0);
    	}
    	int count = adminUserService.deleteSession(session);
    	System.out.println(count);
    	
    	
    	return ResultModel.success(null);
    }

}
